from back_rehabsystem import RehabSystem as rs
from db_DeviceManager import DeviceManager
from db_RehabSystem import RehabSystem
from db_userManager import UserManager
from back_PlanSystem import PlanSystem
from back_DoctorSystem import DoctorSystem


class AuthManager:
    def __init__(self,backend):
        self.backend = backend
        self.user_manager = UserManager()
        self.rehab_system = RehabSystem()  # 新增康复系统实例
        self.plan_system = PlanSystem()
        self.device_manager = DeviceManager()  # 新增设备管理器
        self.doctor_system = DoctorSystem()
        self.backrehabsystem=rs()

    def handle_register(self, username, password, role):
        """
        处理用户注册请求
        参数:
            username: 用户名
            password: 密码
            role: 角色(doctor/therapist/patient)
        返回:
            (success, message) 元组
        """
        valid_roles = ['doctor', 'therapist', 'patient']
        if role not in valid_roles:
            return False, "无效的角色类型"
        try:
            if self.user_manager.user_exists(username):
                return False, "用户名已存在"
            success = self.user_manager.register_user(username, password, role)
            return (True, "注册成功") if success else (False, "注册失败，请联系管理员")
        except Exception as e:
            print(f"注册异常: {e}")
            return False, "系统错误，注册失败"

    def handle_login(self, username, password):
        """
        处理用户登录请求
        参数:
            username: 用户名
            password: 密码
        返回:
            (success, message/data) 元组
        """
        try:
            user = self.user_manager.verify_user(username, password)
            if not user:
                return False, "用户名或密码错误"
            if user['account_status'] != 'active':
                return False, "账户已被禁用"
            return True, {
                'user_id': user['user_id'],
                'username': user['username'],
                'role': user['role'],
                'last_login': user.get('last_login')
            }
        except Exception as e:
            print(f"登录异常: {e}")
            return False, "系统错误，登录失败"

    def handle_password_change(self, username, old_pw, new_pw):
        """
        处理密码修改请求
        参数:
            username: 用户名
            old_pw: 旧密码
            new_pw: 新密码
        返回:
            (success, message) 元组
        """
        try:
            success = self.user_manager.change_password(username, old_pw, new_pw)
            return (True, "密码修改成功") if success else (False, "旧密码验证失败")
        except Exception as e:
            print(f"密码修改异常: {e}")
            return False, "系统错误，密码修改失败"

    def get_user_info(self, username):
        """
        获取用户完整信息
        参数:
            username: 用户名
        返回:
            (success, message/data) 元组
        """
        try:
            user_info = self.user_manager.get_user_info(username)
            if not user_info:
                return False, "用户不存在"
            return True, {
                'user_id': user_info['user_id'],
                'username': user_info['username'],
                'role': user_info['role'],
                'full_name': user_info.get('full_name', ''),
                'account_status': user_info.get('account_status', 'active')
            }
        except Exception as e:
            print(f"获取用户信息异常: {e}")
            return False, "系统错误，获取用户信息失败"

    def deactivate_user(self, username):
        """停用用户账户"""
        try:
            success = self.user_manager.deactivate_user(username)
            return (True, "账户已停用") if success else (False, "用户不存在")
        except Exception as e:
            print(f"停用账户异常: {e}")
            return False, "系统错误，停用账户失败"

    def get_role_dashboard_data(self, user_id, role):
        """
        获取角色仪表盘数据
        参数:
            user_id: 用户ID
            role: 用户角色
        返回:
            字典格式的仪表盘数据，失败返回空字典
        """
        try:
            # 通过RehabSystem获取数据
            return self.rehab_system.get_role_dashboard_data(user_id, role)
        except Exception as e:
            print(f"获取仪表盘数据异常: {e}")
            return self.get_empty_dashboard_data(role)  # 返回空数据模板

    def get_empty_dashboard_data(self, role):
        """返回各角色的空数据模板"""
        templates = {
            'patient': {
                'active_plans': [],
                'latest_feedback': None,
                'progress': []
            },
            'doctor': {
                'patients': [],
                'therapists': [],
                'stats': {}
            },
            'therapist': {
                'devices': [],
                'active_plans': [],
                'upcoming_sessions': []
            }
        }
        return templates.get(role, {})

    def add_new_device(self, therapist_id, device_data):
        return self.backrehabsystem.add_new_device(therapist_id, device_data)

    def edit_device(self, therapist_id, device_id, new_status, new_location):
        return self.backrehabsystem.edit_device(therapist_id, device_id, new_status, new_location)

    def delete_device(self, therapist_id, device_id):
        return self.backrehabsystem.delete_device(therapist_id,device_id)

    def get_patient_list(self, therapist_id):
        return self.plan_system.get_patient_list(therapist_id)

    def add_rehab_plan(self, plan_data):
        return self.plan_system.add_rehab_plan(plan_data)

    def get_patient_plans(self, patient_id):
        return self.plan_system.get_patient_plans(patient_id)

    def update_rehab_plan(self, plan_data):
        return self.plan_system.update_rehab_plan(plan_data)

    def delete_rehab_plan(self, therapist_id, plan_id):
        return self.plan_system.delete_rehab_plan(therapist_id,plan_id)

    def get_plan_with_exercises(self, plan_id):
        return self.plan_system.get_plan_with_exercises(plan_id)

    def add_exercise_to_plan(self, therapist_id, plan_id, exercise_data):
        return self.plan_system.add_exercise_to_plan(therapist_id,plan_id,exercise_data)

    def get_available_therapists(self,doctor_id):
        return self.doctor_system.get_available_therapists(doctor_id)

    def assign_therapist_to_doctor(self,doctor_id,therapist_id):
        return self.doctor_system.assign_therapist_to_doctor(doctor_id,therapist_id)

    def save_new_patient(self, patient_data):
        return self.doctor_system.save_new_patient(patient_data)


